import { Injectable, Component } from '@angular/core';
import { BehaviorSubject, Subject } from 'rxjs';
import { UnifiedMapMode, EntityPickedEvent } from 'unified-map';
import { DisplayComponent } from './display.component';
import { ComponentType } from '@angular/cdk/portal';
import { MapUiService } from '../one-map/map-ui.service';
import { Overlay } from 'ol';

@Injectable({
  providedIn: 'root'
})
export class DisplayService {
  private mView: DisplayComponent;
  private sidePaneComp: Component;

  mapInitialized: BehaviorSubject<UnifiedMapMode> = new BehaviorSubject(
    undefined
  );
  entityClicked: BehaviorSubject<EntityPickedEvent> = new BehaviorSubject(
    undefined
  );
  entityHovered: BehaviorSubject<EntityPickedEvent> = new BehaviorSubject(
    undefined
  );
  readonly sidePaneChange: Subject<any> = new Subject();
  typeChange: Subject<any> = new Subject();

  get mainView(): DisplayComponent {
    return this.mView;
  }

  set mainView(mainView: DisplayComponent) {
    this.mView = mainView;
  }

  get currentSidePaneComp(): Component | any {
    return this.sidePaneComp;
  }

  set currentSidePaneComp(comp: Component | any) {
    this.sidePaneComp = comp;
  }

  constructor(private mapService: MapUiService) { }

  openSidePane(): void {
    if (this.mainView.unifiedMap.sidePaneState === 'close') {
      setTimeout(() => {
        this.mainView.unifiedMap.toggleSide();
      }, 1);
    }
  }

  closeSidePane(): void {
    if (this.mainView.unifiedMap.sidePaneState === 'open') {
      setTimeout(() => {
        this.mainView.unifiedMap.toggleSide();
      }, 1);
    }
  }

  createSidePane<T>(comp: ComponentType<T>, data?: object, defaultOpen = true): void {
    this.sidePaneChange.next({
      component: comp,
      defaultOpen: defaultOpen,
      data: data
    });
  }

  addOverlay(elem, coordinate) {
    const pos = this.mapService.transformCoordinate(coordinate);
    const overlay = new Overlay({
      position: pos,
      element: elem
    });
    this.mapService.olMap.addOverlay(overlay);
  }

  clearOverlay() {
    this.mapService.olMap.getOverlays().clear();
  }
}
